<template>
  <el-row :gutter="20">
    <el-col :span="18">
      <!-- 打卡区域 -->
      <el-card class="punch">
        <div class="header">
          <span>打卡</span>
          <span
            ><el-badge :value="signTimes">
              <el-button>本月签到</el-button>
            </el-badge></span
          >
          <span
            ><el-button v-if="!isClocked" type="primary" @click="clockIn"
              >未打卡</el-button
            >
            <el-button v-else type="success" @click="clockInfo"
              >已打卡</el-button
            ></span
          >
        </div>
        <el-calendar :first-day-of-week="7">
          <template #dateCell="{ data }">
            <p style="text-align: center">
              {{ data.day.split('-').slice(2).join('-') }}<br />
            </p>
            <div v-for="(item, index) in calendarData" :key="index">
              <div
                v-if="data.day === index && !!item"
                style="text-align: center; color: #409eff"
              >
                已签到
              </div>
              <div
                v-if="data.day === index && data.day < newDay && !item"
                style="text-align: center; color: #f56c6c"
              >
                未签到
              </div>
            </div>
          </template>
        </el-calendar>
      </el-card>
      <!-- 图表区域 -->
      <el-card class="figure">
        <span>当月学习分析</span>
        <el-alert
          v-show="learnCondition.code === '888'"
          :title="learnCondition.msg"
          type="warning"
          show-icon
        >
        </el-alert>
        <el-tabs
          style="margin-top: 20px; padding: 0 20px"
          v-model="activeTabName"
        >
          <el-tab-pane style="width: 100%" label="学习分析" name="main1">
            <!-- 为 ECharts 准备一个定义了宽高的 DOM -->
            <div id="main1" style="width: 840px; height: 400px"></div>
          </el-tab-pane>
          <el-tab-pane
            style="width: 100%"
            label="用户本月学习情况"
            name="main2"
          >
            <!-- 为 ECharts 准备一个定义了宽高的 DOM -->
            <div id="main2" style="width: 840px; height: 400px"></div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card class="chicken-box">
        <span>心灵文案</span>
        <p>{{ chicken }}</p>
      </el-card>
      <el-card class="ranking-box">
        <span>学习排行榜</span>
        <el-table :data="rankMessage" style="width: 100%" max-height="320px">
          <el-table-column prop="name" label="用户名" align="center">
          </el-table-column>
          <el-table-column prop="clockNum" label="打卡次数" align="center">
          </el-table-column>
        </el-table>
      </el-card>
      <el-card class="analysis-box" v-show="activeTabName === 'main2'">
        <span>本月学习情况</span>
        <el-collapse v-model="activeCollapseNames">
          <el-collapse-item title="学习时长分析" name="1">
            <div v-show="studyAnalysis.studyAllTime">
              学习总时长： <i>{{ studyAnalysis.studyAllTime + ' 小时' }}</i>
            </div>
            <div v-show="studyAnalysis.maxDayStudyTime">
              日学习最大时长：
              <i>{{ studyAnalysis.maxDayStudyTime + ' 小时' }}</i>
            </div>
            <div v-show="studyAnalysis.maxTimeSlot">
              学习高峰期：<i>{{ studyAnalysis.maxTimeSlot }}</i>
            </div>
          </el-collapse-item>
          <el-collapse-item title="学习内容分析" name="2">
            <div v-show="studyAnalysis.bestLikeStudyContent">
              最爱学习内容：<i>{{ studyAnalysis.bestLikeStudyContent }}</i>
            </div>
            <div v-show="studyAnalysis.isLikeTag">
              最爱标签：<i>{{ studyAnalysis.isLikeTag }}</i>
            </div>
          </el-collapse-item>
          <el-collapse-item title="学习总结" name="3">
            <div v-show="studyAnalysis.summary">
              <i>{{ studyAnalysis.summary }}</i>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { useStore } from 'vuex';
import * as echarts from 'echarts';
import { dataFormat } from '@/utils/data';
import { ref, getCurrentInstance, ComponentInternalInstance, reactive, onMounted, watch, computed } from 'vue';
import store from '@/store';
const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;

const storeData = useStore();

// 用户id
const id = ref(proxy.$storage.getItem('userInfo').userId);
// 签到人数
const clockPeopleNum = ref(0);
// 记录当前日期
const newDay = ref('');
// 本月签到次数
const signTimes = ref(0);
// 活跃标签页的名字
let activeTabName = ref(proxy.$storage.getItem('activeTabName') || 'main1');
// 用户本月学习情况
interface LearnCondition {
  code: String
  msg: String
}
const learnCondition = reactive<LearnCondition>({
  code: '',
  msg: '',
})
// 鸡汤文案
const chicken = ref('');
// 活跃的面板名
const activeCollapseNames = ref([]);
// 学习分析
interface StudyAnalysis {
  // 学习总时长
  studyAllTime: String
  // 日学习最大时长
  maxDayStudyTime: String
  // 学习高峰期
  maxTimeSlot: String
  // 最爱学习内容
  bestLikeStudyContent: String
  // 最爱标签
  isLikeTag: String
  // 学习总结
  summary: String
}
const studyAnalysis = reactive<StudyAnalysis>({
  // 学习总时长
  studyAllTime: '',
  // 日学习最大时长
  maxDayStudyTime: '',
  // 学习高峰期
  maxTimeSlot: '',
  // 最爱学习内容
  bestLikeStudyContent: '',
  // 最爱标签
  isLikeTag: '',
  // 学习总结
  summary: '',
});


//  const data = reactive([{ name: 'txk', clockNum: 1 }])

onMounted(() => {
  newDay.value = dataFormat();
  initEcharts1();
  initEcharts2();

  getMothLive();
  getChicken();
})

const isClocked = computed(() => storeData.state.userSign.isClocked)
const calendarData = computed(() => storeData.state.userSign.calendarData) // 获取 state中的值
const rankMessage = computed(() => storeData.state.userSign.rankMessage)

watch(activeTabName, (newValue: any) => {
  proxy.$storage.setItem('activeTabName', newValue);
});

// ...mapActions('userSign', ['getSignInfo', 'getRank']),
// 获取用户本月签到次数
function getMothLive() {
  proxy.$request.userSign.mothLive(id.value).then((res: any) => {
    signTimes.value = res.data;
  });
};
// 点击按钮后打卡
function clockIn() {
  proxy.$request.userSign.someday(id.value).then((res: any) => {
    proxy.$request.userSign.sameday().then((resp: any) => {
      proxy.$alert(
        `<span style="margin-left: 40px;font-size: 16px">恭喜您为第 <strong>${resp.data}</strong> 位签到的用户，请继续加油呦！</span>`,
        '签到信息',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
        }
      );
      clockPeopleNum.value = resp.data;
    });
    store.dispatch('userSign/getSignInfo', { data: id.value })
    store.dispatch('userSign/getRank');
    // this.getSignInfo({ data: this.id });
    // this.getRank();
    getMothLive();
    initEcharts1();
    initEcharts2();
    proxy.$message.success(res.msg);
  });
};
// 获取鸡汤
function getChicken() {
  proxy.$request.chicken.getChicken().then((res: any) => {
    chicken.value = res.data;
  });
};
// 点击已打卡按钮获取用户签到人数信息
function clockInfo() {
  proxy.$request.userSign.sameday().then((res: any) => {
    proxy.$alert(
      `<span style="margin-left: 85px;font-size:16px">当前已签到总人数为：<strong>${res.data}</strong></span>`,
      '签到人数信息',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        callback: () => { },
      }
    );
    clockPeopleNum.value = res.data;
  });
};
// 获取用户当日学习分析echarts图表信息
function initEcharts1() {
  var chartDom1 = document.getElementById('main1');
  var myChart1 = echarts.init(chartDom1);
  // 使用刚指定的配置项和数据显示图表。
  myChart1.setOption({
    title: {
      text: '学习分析',
      subtext: '总体数据',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '学习数据',
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  });
  proxy.$request.userSign
    .mothLive(proxy.$storage.getItem('userInfo').userId)
    .then((res1: any) => {
      console.log('res1===>', res1);
      proxy.$request.discussPost
        .own(
          { pageNum: 1, pageSize: 1 },
          proxy.$storage.getItem('userInfo').userId
        )
        .then((res2: any) => {
      console.log('res2===>', res2);
          myChart1.setOption({
            series: [
              {
                data: [
                  { name: '用户本月签到次数', value: res1.data },
                  {
                    name: '用户发布帖子总数',
                    value: res2.data ? res2.data.total : 0,
                  },
                ],
              },
            ],
          });
        });
    });
};
// 获取用户本月学习情况echarts图表信息
function initEcharts2() {
  // 使用刚指定的配置项和数据显示图表
  proxy.$request.userStudyAnalysis
    .getStudyAnalysis({ userId: proxy.$storage.getItem('userInfo').userId })
    .then((res: any) => {
      console.log('res===>', res);
      learnCondition.code = res.code;
      learnCondition.msg = res.msg;
      if (res.code === '888') return;
      studyAnalysis.studyAllTime = (
        res.data.studyAllTime / 3600
      ).toFixed(2);
      studyAnalysis.maxDayStudyTime = (
        res.data.maxDayStudyTime / 3600
      ).toFixed(2);
      studyAnalysis.maxTimeSlot = res.data.maxTimeSlot;
      studyAnalysis.bestLikeStudyContent =
        res.data.bestLikeStudyContent;
      studyAnalysis.isLikeTag = res.data.isLikeTag;
      studyAnalysis.summary = res.data.summary;
      var chartDom2 = document.getElementById('main2');
      var myChart2 = echarts.init(chartDom2);
      myChart2.setOption({
        // 标题
        title: {
          text: '每天学习时长',
        },
        // 配置每天对应点的弹出框
        tooltip: {
          trigger: 'axis',
          formatter: function (params: any) {
            return (
              params[0].name +
              '<br/>' +
              '学习时长：' +
              params[0].value +
              '小时<br/>' +
              '学习内容：' +
              // 当天学习内容
              res.data.studyContent[params[0].dataIndex]
            );
          },
        },
        // x轴
        xAxis: {
          type: 'category',
          boundaryGap: false,
          // x轴坐标数据（即当月时间）
          data: getDay(res.data.day),
        },
        // y轴
        yAxis: {
          type: 'value',
          // 学习时长，y轴坐标点会按照数据自动填补y轴坐标点
          axisLabel: {
            formatter: '{value} 小时',
          },
        },
        // 数据
        series: [
          {
            // 每日学习时长
            data: getStudyTime(res.data.studyTime),
            // 类型为折现图
            type: 'line',
            // 折现是否平滑
            smooth: true,
          },
        ],
      });
    });
};
// 获取本月日数
function getDay(data: any) {
  const day: any = [];
  data.forEach((item: any) => {
    day.push(item.toString() + '日');
  });
  return day;
};
// 获取本月每天学习时长
function getStudyTime(data: any) {
  const studyTime: any = [];
  data.forEach((item: any) => {
    item = item / 3600;
    studyTime.push(item.toFixed(2));
  });
  return studyTime;
};
</script>

<style lang="less" scoped>
.punch {
  /deep/ .el-calendar-table .el-calendar-day {
    height: 60px;
  }

  .header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;

    span {
      font-size: 20px;
      font-weight: 600;
    }
  }

  .el-calendar {
    p {
      margin: 0 0 3px 0;
    }

    div {
      font-family: 'Helvetica Neue';
      font-size: 14px;
      font-weight: 600;
    }
  }
}

.figure {
  min-height: 200px;
  margin-top: 20px;

  span:nth-child(1) {
    font-size: 20px;
    font-weight: 600;
    display: block;
    margin-bottom: 20px;
  }
}

.chicken-box,
.ranking-box,
.analysis-box {
  span {
    display: block;
    margin-bottom: 10px;
    font-weight: 600;
  }
}

.chicken-box {
  margin-bottom: 10px;
  height: 180px;

  p {
    font-family: '宋体';
    padding: 0 11px;
    font-size: 16px;
    color: #e6a23c;
    overflow-wrap: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 6;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
}

.ranking-box {
  height: 400px;
}

.analysis-box {
  margin-top: 20px;

  .el-collapse {
    .el-collapse-item__header {
      font-size: 18px;
    }

    .el-collapse-item {
      div {
        font-family: '微软雅黑';
        font-size: 14px;
        padding: 0 10px;

        i {
          font-family: '宋体';
        }
      }
    }
  }
}
</style>
